// 用于从ist.tn上同步设置到gui 很简单了

const https=require('https');
const http=require('http');
const fs=require('fs');

init()

async function init(){
  
  let url=await getRealUrl()
  let html=await getHtml(url)
  let newVmess=getVmess(html)
  let LocalConfig=getLocalConfig()
  LocalConfig.vmess=[];
  for (let item of newVmess){
    LocalConfig.vmess.push({ configVersion: 2,
      address: item.add,
      port: parseInt(item.port),
      id: item.id,
      alterId:item.aid,
      security: 'auto',
      network: item.net,
      remarks: item.ps,
      headerType: item.type,
      requestHost: item.host,
      path: item.path,
      streamSecurity: item.tls,
      allowInsecure: '',
      configType: 1,
      testResult: '',
      subid: '' 
    })
  }
  LocalConfig.index=newVmess.length-1
  setLocalconfig(LocalConfig)
  console.log('ok')
}

function getLocalConfig(){
  return JSON.parse(fs.readFileSync('./guiNconfig.json'))
}

function setLocalconfig(obj){
  fs.writeFileSync('./guiNconfig.json',JSON.stringify(obj),{
    encoding:'utf8',
    flag:'w'
  })
}

function getRealUrl(){
  return new Promise((resolve,reject)=>{
    http.get('http://isx.tn/',(res)=>{
      resolve(res.headers['location'])
      
    })
  })
}

function getHtml(url){
  return new Promise((resolve,reject)=>{
    https.get(url,(res)=>{
      let html=''
      res.on('data',(data)=>{
        html+=data
      })
      res.on('end',()=>{
        resolve(html)
      })
    })
  })
}

function getVmess(html){
  let reg=/data\-clipboard\-text\=\"vmess\:\/\/(.+)/g
  let vmesss=html.match(reg)
  vmesss=vmesss.map((item)=>{
    return JSON.parse(new Buffer(item.replace('data-clipboard-text="vmess://',''),'base64').toString())
  })
  return vmesss
}

